package com.ruoyi.system.controller;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import com.ruoyi.common.utils.NewDateUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.AlpContractDetailWithMonth;
import com.ruoyi.system.domain.vo.AlpContractDetailWithWeek;
import com.ruoyi.system.mapper.AlpYingshouMapper;
import com.ruoyi.system.service.*;
import io.swagger.models.auth.In;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 合同表管理Controller
 * 
 * @author zhangjun
 * @date 2020-02-13
 */
@Controller
@RequestMapping("/system/contractDetail")
public class AlpContractDetailController extends BaseController
{
    private String prefix = "system/contractDetail";

    private static final Integer year = 2020;

    @Autowired
    private IAlpContractDetailService alpContractDetailService;

    @Autowired
    private IAlpContractStageService alpContractStageService;

    @Autowired
    private IAlpContractStageDetailService alpContractStageDetailService;


    @Autowired
    private IAlpYingshouService alpYingshouService;


    @RequiresPermissions("system:contractDetail:view")
    @GetMapping("/new")
    public String contractDetailNew()
    {
        return prefix + "/contractDetailNew";
    }

    @RequiresPermissions("system:contractDetail:view")
    @GetMapping()
    public String contractDetail()
    {
        return prefix + "/contractDetail";
    }

    /**
     * 查询合同表管理列表
     */
    @RequiresPermissions("system:contractDetail:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(AlpContractDetail alpContractDetail)
    {
        startPage();
        List<AlpContractDetail> list = alpContractDetailService.selectAlpContractDetailList(alpContractDetail);
        Integer count = alpContractDetailService.selectAllCount(alpContractDetail);
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setCode(0);
        tableDataInfo.setRows(list);
        tableDataInfo.setTotal(count);
        return tableDataInfo;
    }

    /**
     * 导出合同表管理列表
     */
    @RequiresPermissions("system:contractDetail:export")
    @Log(title = "合同表管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(AlpContractDetail alpContractDetail)
    {
        List<AlpContractDetail> list = alpContractDetailService.selectAlpContractDetailList(alpContractDetail);
        ExcelUtil<AlpContractDetail> util = new ExcelUtil<AlpContractDetail>(AlpContractDetail.class);
        return util.exportExcel(list, "contractDetail");
    }

    /**
     * 导出合同表--包含周度预算
     */
    @RequiresPermissions("system:contractDetail:export")
    @Log(title = "导出周度预算", businessType = BusinessType.EXPORT)
    @PostMapping("/exportWeekBudget")
    @ResponseBody
    public AjaxResult exportWeekBudget(AlpContractDetail alpContractDetail) {
        List<AlpContractDetail> list = alpContractDetailService.selectAlpContractDetailList(alpContractDetail);
        List<AlpContractDetailWithWeek> listBasic = new ArrayList<>();
        try {
            Field[] fields = AlpContractDetailWithWeek.class.getDeclaredFields();
            for (AlpContractDetail contractDetail : list) {
                AlpContractDetailWithWeek contractDetailWithWeek = new AlpContractDetailWithWeek();
                BeanUtils.copyProperties(contractDetail, contractDetailWithWeek);
                for (int i = 1; i <= 53; i++) {
                    for (Field field : fields) {
                        String fieldName = field.getName();
                        if (!fieldName.startsWith("week")) {
                            continue;
                        }
                        if (i == Integer.valueOf(fieldName.substring(4))) {
                            field.set(contractDetailWithWeek, alpYingshouService.calcEachWeekSumBudget(i, contractDetail.getContractId(), year));
                        }
                    }
                }
                listBasic.add(contractDetailWithWeek);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        ExcelUtil<AlpContractDetailWithWeek> util = new ExcelUtil<AlpContractDetailWithWeek>(AlpContractDetailWithWeek.class);
        return util.exportExcel(listBasic, "周度预算");
    }

    /**
     * 导出合同表--包含周度预测
     */
    @RequiresPermissions("system:contractDetail:export")
    @Log(title = "导出周度预测", businessType = BusinessType.EXPORT)
    @PostMapping("/exportWeekPredict")
    @ResponseBody
    public AjaxResult exportWeekPredict(AlpContractDetail alpContractDetail) {
        List<AlpContractDetail> list = alpContractDetailService.selectAlpContractDetailList(alpContractDetail);
        List<AlpContractDetailWithWeek> listBasic = new ArrayList<>();
        try {
            Field[] fields = AlpContractDetailWithWeek.class.getDeclaredFields();
            for (AlpContractDetail contractDetail : list) {
                AlpContractDetailWithWeek contractDetailWithWeek = new AlpContractDetailWithWeek();
                BeanUtils.copyProperties(contractDetail, contractDetailWithWeek);
                for (int i = 1; i <= 53; i++) {
                    for (Field field : fields) {
                        String fieldName = field.getName();
                        if (!fieldName.startsWith("week")) {
                            continue;
                        }
                        if (i == Integer.valueOf(fieldName.substring(4))) {
                            field.set(contractDetailWithWeek, alpYingshouService.calcEachWeekSumPredict(i, contractDetail.getContractId(), year));
                        }
                    }
                }
                listBasic.add(contractDetailWithWeek);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        ExcelUtil<AlpContractDetailWithWeek> util = new ExcelUtil<AlpContractDetailWithWeek>(AlpContractDetailWithWeek.class);
        return util.exportExcel(listBasic, "周度预测");
    }

    /**
     * 导出合同表--包含周度实际
     */
    @RequiresPermissions("system:contractDetail:export")
    @Log(title = "导出周度实际", businessType = BusinessType.EXPORT)
    @PostMapping("/exportWeekActual")
    @ResponseBody
    public AjaxResult exportWeekActual(AlpContractDetail alpContractDetail) {
        List<AlpContractDetail> list = alpContractDetailService.selectAlpContractDetailList(alpContractDetail);
        List<AlpContractDetailWithWeek> listBasic = new ArrayList<>();
        try {
            Field[] fields = AlpContractDetailWithWeek.class.getDeclaredFields();
            for (AlpContractDetail contractDetail : list) {
                AlpContractDetailWithWeek contractDetailWithWeek = new AlpContractDetailWithWeek();
                BeanUtils.copyProperties(contractDetail, contractDetailWithWeek);
                for (int i = 1; i <= 53; i++) {
                    for (Field field : fields) {
                        String fieldName = field.getName();
                        if (!fieldName.startsWith("week")) {
                            continue;
                        }
                        if (i == Integer.valueOf(fieldName.substring(4))) {
                            field.set(contractDetailWithWeek, alpYingshouService.calcEachWeekSumActual(i, contractDetail.getContractId(), year));
                        }
                    }
                }
                listBasic.add(contractDetailWithWeek);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        ExcelUtil<AlpContractDetailWithWeek> util = new ExcelUtil<AlpContractDetailWithWeek>(AlpContractDetailWithWeek.class);
        return util.exportExcel(listBasic, "周度实际");
    }

    /**
     * 导出合同表--包含月度预算
     */
    @RequiresPermissions("system:contractDetail:export")
    @Log(title = "导出月度预算", businessType = BusinessType.EXPORT)
    @PostMapping("/exportMonthBudget")
    @ResponseBody
    public AjaxResult exportMonthBudget(AlpContractDetail alpContractDetail) {
        List<AlpContractDetail> list = alpContractDetailService.selectAlpContractDetailList(alpContractDetail);
        List<AlpContractDetailWithMonth> listBasic = new ArrayList<>();
        try {
            Field[] fields = AlpContractDetailWithMonth.class.getDeclaredFields();
            for (AlpContractDetail contractDetail : list) {
                AlpContractDetailWithMonth contractDetailWithMonth = new AlpContractDetailWithMonth();
                BeanUtils.copyProperties(contractDetail, contractDetailWithMonth);
                for (int i = 1; i <= 12; i++) {
                    for (Field field : fields) {
                        String fieldName = field.getName();
                        if (!fieldName.startsWith("month")) {
                            continue;
                        }
                        if (i == Integer.valueOf(fieldName.substring(5))) {
                            field.set(contractDetailWithMonth, alpYingshouService.calcEachMonthSumBudget(i, contractDetail.getContractId(), year));
                        }
                    }
                }
                listBasic.add(contractDetailWithMonth);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        ExcelUtil<AlpContractDetailWithMonth> util = new ExcelUtil<>(AlpContractDetailWithMonth.class);
        return util.exportExcel(listBasic, "月度预算");
    }

    /**
     * 导出合同表--包含月度预测
     */
    @RequiresPermissions("system:contractDetail:export")
    @Log(title = "导出月度预测", businessType = BusinessType.EXPORT)
    @PostMapping("/exportMonthPredict")
    @ResponseBody
    public AjaxResult exportMonthPredict(AlpContractDetail alpContractDetail) {
        List<AlpContractDetail> list = alpContractDetailService.selectAlpContractDetailList(alpContractDetail);
        List<AlpContractDetailWithMonth> listBasic = new ArrayList<>();
        try {
            Field[] fields = AlpContractDetailWithMonth.class.getDeclaredFields();
            for (AlpContractDetail contractDetail : list) {
                AlpContractDetailWithMonth contractDetailWithMonth = new AlpContractDetailWithMonth();
                BeanUtils.copyProperties(contractDetail, contractDetailWithMonth);
                for (int i = 1; i <= 12; i++) {
                    for (Field field : fields) {
                        String fieldName = field.getName();
                        if (!fieldName.startsWith("month")) {
                            continue;
                        }
                        if (i == Integer.valueOf(fieldName.substring(5))) {
                            field.set(contractDetailWithMonth, alpYingshouService.calcEachMonthSumPredict(i, contractDetail.getContractId(), year));
                        }
                    }
                }
                listBasic.add(contractDetailWithMonth);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        ExcelUtil<AlpContractDetailWithMonth> util = new ExcelUtil<>(AlpContractDetailWithMonth.class);
        return util.exportExcel(listBasic, "月度预测");
    }

    /**
     * 导出合同表--包含月度实际
     */
    @RequiresPermissions("system:contractDetail:export")
    @Log(title = "导出月度实际", businessType = BusinessType.EXPORT)
    @PostMapping("/exportMonthActual")
    @ResponseBody
    public AjaxResult exportMonthActual(AlpContractDetail alpContractDetail) {
        List<AlpContractDetail> list = alpContractDetailService.selectAlpContractDetailList(alpContractDetail);
        List<AlpContractDetailWithMonth> listBasic = new ArrayList<>();
        try {
            Field[] fields = AlpContractDetailWithMonth.class.getDeclaredFields();
            for (AlpContractDetail contractDetail : list) {
                AlpContractDetailWithMonth contractDetailWithMonth = new AlpContractDetailWithMonth();
                BeanUtils.copyProperties(contractDetail, contractDetailWithMonth);
                for (int i = 1; i <= 12; i++) {
                    for (Field field : fields) {
                        String fieldName = field.getName();
                        if (!fieldName.startsWith("month")) {
                            continue;
                        }
                        if (i == Integer.valueOf(fieldName.substring(5))) {
                            field.set(contractDetailWithMonth, alpYingshouService.calcEachMonthSumActual(i, contractDetail.getContractId(), year));
                        }
                    }
                }
                listBasic.add(contractDetailWithMonth);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        ExcelUtil<AlpContractDetailWithMonth> util = new ExcelUtil<>(AlpContractDetailWithMonth.class);
        return util.exportExcel(listBasic, "月度实际");
    }

    /**
     * 导出合同表管理列表
     */
    @RequiresPermissions("system:contractDetail:export")
    @Log(title = "应收账款", businessType = BusinessType.EXPORT)
    @PostMapping("/exportYingShou")
    @ResponseBody
    public AjaxResult exportYingShou(AlpContractDetail alpContractDetail)
    {
        List<AlpYingshou> yingShouList = new ArrayList<AlpYingshou>();
        List<AlpContractDetail> list = alpContractDetailService.selectAlpContractDetailList(alpContractDetail);
        for (AlpContractDetail contractDetail : list) {
            //根据合同id 查出本合同的阶段表内容
            List<AlpContractStage> contractStages = alpContractStageService.selectAlpContractStageByContractId(contractDetail.getContractId());
            for (AlpContractStage contractStage : contractStages) {
                AlpYingshou yingshou = new AlpYingshou();
                //根据阶段id 查出阶段最新的预测预算实际
                List<AlpContractStageDetail> stageDetails = alpContractStageDetailService.selectAlpContractStageDetailByStageId(contractStage.getStageId());

                contractStage.setAlpContractStageDetails(stageDetails);

//                yingshou.setDepartment(contractDetail);
                yingshou.setStageName(contractStage.getStageName());
                yingshou.setSalesmanFirst(contractStage.getStagePrincipal1());
                yingshou.setSalesmanSecond(contractStage.getStagePrincipal2());
                yingshou.setCollectionCompany(contractDetail.getBiddingCompany());//逻辑错误
                yingshou.setCustomerName(contractDetail.getPartyAName());
                yingshou.setContractNo(contractDetail.getContractNo());
                yingshou.setContractName(contractDetail.getContractName());
                yingshou.setContractMoney(contractDetail.getBiddingMoney());

                yingShouList.add(yingshou);
            }

        }

        ExcelUtil<AlpYingshou> util = new ExcelUtil<AlpYingshou>(AlpYingshou.class);
        return util.exportExcel(yingShouList, "应收表");
    }


    /**
     * 新增合同表管理
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存合同表管理
     */
    @RequiresPermissions("system:contractDetail:add")
    @Log(title = "合同表管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(AlpContractDetail alpContractDetail)
    {
        if (null == alpContractDetail.getContractSignTime()) {
            return error("合同签订时间不能为空");
        }
        String year = NewDateUtils.format(alpContractDetail.getContractSignTime(), NewDateUtils.YYYY);
        alpContractDetail.setContractSignedInyear(Integer.valueOf(year).toString());
        return toAjax(alpContractDetailService.insertAlpContractDetail(alpContractDetail));
    }

    /**
     * 修改合同表管理
     */
    @GetMapping("/edit/{contractId}")
    public String edit(@PathVariable("contractId") Long contractId, ModelMap mmap)
    {
        AlpContractDetail alpContractDetail = alpContractDetailService.selectAlpContractDetailById(contractId);
        alpContractDetail.setUserId(ShiroUtils.getSysUser().getUserId());
        mmap.put("alpContractDetail", alpContractDetail);
        return prefix + "/edit";
    }

    /**
     * 修改保存合同表管理
     */
    @RequiresPermissions("system:contractDetail:edit")
    @Log(title = "合同表管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(AlpContractDetail alpContractDetail)
    {
        alpContractDetail.setUserId(ShiroUtils.getSysUser().getUserId());
        return toAjax(alpContractDetailService.updateAlpContractDetail(alpContractDetail));
    }

    /**
     * 删除合同表管理
     */
    @RequiresPermissions("system:contractDetail:remove")
    @Log(title = "合同表管理", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(alpContractDetailService.deleteAlpContractDetailByIds(ids));
    }

    /**
     * 可编辑表格--管理合同预算、预测、实际回款金额
     */
    @GetMapping("/moneyBack/{contractId}")
    public String editTableBudget(@PathVariable("contractId") Long contractId, ModelMap mmap)
    {
        AlpContractDetail alpContractDetail = alpContractDetailService.selectAlpContractDetailById(contractId);
        mmap.put("contractSignTime", alpContractDetail.getContractSignTime() == null ? "未填写" : NewDateUtils.format(alpContractDetail.getContractSignTime(), NewDateUtils.FORMAT_STRING_DATELESS));
        mmap.put("firstAcceptanceTime", alpContractDetail.getFirstAcceptanceTime() == null ? "未填写" : NewDateUtils.format(alpContractDetail.getFirstAcceptanceTime(), NewDateUtils.FORMAT_STRING_DATELESS));
        mmap.put("finialAcceptanceTime", alpContractDetail.getFinialAcceptanceTime() == null ? "未填写" : NewDateUtils.format(alpContractDetail.getFinialAcceptanceTime(), NewDateUtils.FORMAT_STRING_DATELESS));
        mmap.put("alpContractDetail", alpContractDetail);
        List<AlpContractStage> list = alpContractStageService.selectAlpContractStageByContractId(contractId);
        mmap.put("stageList", list);
        return prefix + "/moneyBack";
    }

    @Autowired
    ISysUserService sysUserService;
    @GetMapping("/getPerson")
    @ResponseBody
    public List<SysUser> getPerson()
    {
        SysUser user = new SysUser();
        List<SysUser> ret = new ArrayList<>();
        ret = sysUserService.selectUserList(user);
        return ret;
    }

}
